package com.gimi.cloud.bbp.client.service.product.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gimi.cloud.bbp.client.service.product.CategoryService;
import com.gimi.cloud.bbp.common.utils.StringUtil;
import com.gimi.cloud.bbp.dao.dao.prod.EcProdCategoryDao;
import com.gimi.cloud.bbp.dto.prod.EcProdCategoryDTO;

@Service
public class CategoryServiceImpl implements CategoryService {

    private final EcProdCategoryDao categoryDao;

    @Autowired
    public CategoryServiceImpl(EcProdCategoryDao categoryDao){
        this.categoryDao = categoryDao;
    }
    
    @Override
	public List<EcProdCategoryDTO> firstGradeCategories() {
	     List<EcProdCategoryDTO> result = categoryDao.getCategoriesByGrade(1);
	     if(result != null && result.size() >0){
	    	 for(EcProdCategoryDTO cate : result){
	    		 if(cate != null && StringUtil.isNotBlank(cate.getProdCatId())){
	    			 cate.setChildCategorys(categoryDao.getChildCategoriesByParentId(cate.getProdCatId()));
	    		 }
	    	 }
	     }
	     return result;
	}


	@Override
	public List<EcProdCategoryDTO> secondGradeCategories(EcProdCategoryDTO prodCategoryDTO) {
		return categoryDao.getChildCategoriesByParentId(prodCategoryDTO.getParentCatId());
	}
    
	@Override
	public Collection<EcProdCategoryDTO> getHomePageCategories(){
		List<EcProdCategoryDTO> allCate = categoryDao.getHomePageCategories();
		Map<String, EcProdCategoryDTO> rootCate = new LinkedHashMap<>();
		if(allCate != null){
			ListIterator<EcProdCategoryDTO> iterator = allCate.listIterator();
			EcProdCategoryDTO temp;
			Integer rootCatGrade = 1;
			while(iterator.hasNext()){
				temp = iterator.next();
				if(rootCatGrade.equals(temp.getCatGrade())){
					temp.setCatGrade(null);
					rootCate.put(temp.getProdCatId(), temp);
					iterator.remove();
				}else{
					temp.setCatGrade(null);
				}
			}
			EcProdCategoryDTO tempChild;
			while(iterator.hasPrevious()){
				temp = iterator.previous();
				tempChild = rootCate.get(temp.getParentCatId());
				if(tempChild != null){
					if(tempChild.getChildCategorys() == null){
						tempChild.setChildCategorys(new ArrayList<>());
					}
					tempChild.getChildCategorys().add(temp);
				}
			}
		}
		return rootCate.values();
	}
}
